/***************************************************************************************************
  *Copyright(C),2010-2016,Sumscope
  *FileName	:  JsonWideWriter.cpp
  *Author	:  scofined.qi
  *Version	:  1.0
  *Date		:  2016/09/12
  *Desc		:  //用于主要说明此程序文件完成的主要功能
  *Relation :  
  *Others	:  //其他内容说明
  *Function :  //主要函数列表，每条记录应包含函数名及功能简要说明
  *History	:  //修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简介
***************************************************************************************************/
#include "JsonWideWriter.h"

qb::base::JsonWideWriter::JsonWideWriter(int initCapcity /*= 0*/) :m_count(0), m_finished(false), m_rootmap(false),
m_rootlist(false)
{
	initCapcity = (initCapcity > 0 && initCapcity < 16 * 1024 * 1024) ? initCapcity : 0;
	m_buffer = new Buffer(initCapcity);
}

qb::base::JsonWideWriter::~JsonWideWriter()
{
	if (m_buffer)	delete m_buffer;
}

int qb::base::JsonWideWriter::GetCapcity() const
{
	return m_buffer->getcapcity();
}

void qb::base::JsonWideWriter::Start(int capcity)
{
#ifndef WIN32
    static 	const Element	MAP_START = L'{';
#endif

	m_count = 0;
	m_finished = false;
	m_buffer->clear();
	m_buffer->setcapcity(capcity);
	memset(m_buffer->GetBuffer(), 0, m_buffer->getcapcity()*sizeof(Element));
	AddString(&MAP_START, 1);
}

const qb::base::JsonWideWriter::Element* qb::base::JsonWideWriter::c_str()
{
#ifndef WIN32
    static 	const Element	MAP_END = L'}';
#endif

	if (!m_finished){ m_finished = true; 
	if (!m_rootmap && !m_rootlist)AddString(&MAP_END, 1); }

	return m_buffer->GetBuffer();
}

int qb::base::JsonWideWriter::size()
{
#ifndef WIN32
    static 	const Element	MAP_END = L'}';
#endif

	if (!m_finished){ 
		m_finished = true; 
		if (!m_rootmap&& !m_rootlist)AddString(&MAP_END, 1);
	}
	return m_buffer->size();
}

void qb::base::JsonWideWriter::AddJsonString(const Element* str, int len /*= 0*/)
{
#ifndef WIN32
    static  const Element   QUOTATION = L'"';
#endif

	AddString(&QUOTATION, 1);
	len = str ? (len <= 0 ? wcslen(str) : len) : 0;
	if (len > 0)
	{
		for (int i = 0; i < len; i++)
		{
			const Element& t = str[i];
			if (t == (Element)'\\' || t == (Element)'"'){ m_buffer->Add((Element)'\\'); m_buffer->Add(t); }
			else if (t == (Element)'\r'){ m_buffer->Add((Element)'\\'); m_buffer->Add((Element)'r'); }
			else if (t == (Element)'\n'){ m_buffer->Add((Element)'\\'); m_buffer->Add((Element)'n'); }
			else m_buffer->Add(t);
		}
	}
	AddString(&QUOTATION, 1);
}

void qb::base::JsonWideWriter::AddString(const Element* str, int len/*=0*/)
{
	if (str)
	{
		len = len <= 0 ? wcslen(str) : len;
		if (len > 0)
		{
			m_buffer->append(str, len);
		}
	}
}
